import { defineStore } from 'pinia'

import { loginApi, logoutApi, postResumeFileApi,getUserInfoApi } from '@/api/user'
import type { UserInfo, LoginData } from '@/api/user/types'
import { resetRouter } from '@/router'
import { store } from '@/store'

//响应式的本地存储！！！
import { useStorage } from '@vueuse/core'

export const useUserStore = defineStore('user', () => {
  //用户信息
  const user: any = reactive({})

  //存储一份AI简历分析结果
  const resumeResult:any=ref({})
  const ttsWS:any=ref('close')

  const token = useStorage('accessToken', '')
  // Message界面状态变量
  const itemData = ref({})

  // job-recommend界面infoShow状态数据
  const jobData = ref({})
   // update itemData
   function updateItemData(item: Object) {
    itemData.value = item
  }
  function updateJobData(job: Object) {
    jobData.value = job
  }
  
  /* 登录状态用本地存储了 */
  let isLogin = useStorage("isLogin", false)
  //计算出一个登录身份
  let signType=computed(()=>{
    return user.basicInfo?.signType
  })
// 普通用户使用虚拟面试次数,最初为3次
  const virtualInterviewTimes = useStorage('virtualInterviewTimes', 3)
// vip 
  const vip = useStorage('vip', false)
// 普通用户使用AI智能诊断次数,最初为3次
  const aiDiagnosisTimes = useStorage('aiDiagnosisTimes', 3)
  const aiDiagnosisTimes2 = useStorage('aiDiagnosisTimes2', 3)
  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((response) => {
          console.log(response)

          //存储到状态库中
          // user.data = response
          //登录状态为true
          isLogin.value = true
          token.value = response.data.token // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve(response.data as any)
        })
        .catch((error) => {
          console.log('KKKk')

          reject(error)
        })
    })
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfoApi()
        .then((response) => {
          

          const { basicInfo, educationInfo, forJobInfo } = response.data

          // if (!data) {
          //   reject("Verification failed, please Login again.");
          //   return;
          // }
          // if (!data.roles || data.roles.length <= 0) {
          //   reject("getUserInfo: roles must be a non-null array!");
          //   return;
          // }
          // Object.assign(user, { ...data });
          //信息存到状态管理库中
          let data = response.data.data as any

          Object.assign(user, { ...data });
          resolve(response.data as any)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // user logout
  function logout() {
    // 模拟进行登出
    isLogin.value = false
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          isLogin.value = false
          token.value = ''
          location.reload() // 清空路由
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      token.value = ''
      resetRouter()
      resolve()
    })
  }
 
  function postResumeFile(file: File) {
    return new Promise<void>((resolve, reject) => {
      postResumeFileApi(file)
        .then((response) => {
          if (response.data !== null) {
            resolve(response.data as any)
          } else {
            reject('错误!')
          }
        })
        .catch((err) => console.log(err))
    })
  }

  
  return {
    token,
    user,
    virtualInterviewTimes,
    vip,
    postResumeFile,
    jobData,
    updateItemData,
    updateJobData,
    login,
    getUserInfo,
    logout,
    resetToken,
    aiDiagnosisTimes,
    aiDiagnosisTimes2,
    isLogin,
    signType,
    resumeResult,
    ttsWS
  }
},{
  persist: true,
})

// 非setup
export function useUserStoreHook() {
  return useUserStore(store)
}
